package com.zaofan.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zaofan.bean.Admin;
import com.zaofan.exception.ServiceException;
import com.zaofan.service.AdminService;
import com.zaofan.utils.JsonUtils;
import com.zaofan.utils.WebUtils;

@WebServlet("/admin")
public class AdminController extends BaseServlet {
	private static final long serialVersionUID = 1L;
	private AdminService adminService = new AdminService();

	protected void login(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			Admin admin = WebUtils.write2bean(request, Admin.class);
			Admin target = adminService.login(admin);
			request.getSession().setAttribute("admin", target);
			JsonUtils.writeSuccessJson("查询成功", target, response);
		} catch (ServiceException se) {
			se.printStackTrace();
			JsonUtils.writeBeanFailJson(se.getMessage(), response);
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeBeanFailJson("参数错误!!", response);
		}
		JsonUtils.writeBeanFailJson("查询失败!!", response);
	}

	protected void modifyPass(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			Integer id = Integer.valueOf(request.getParameter("id"));
			String oldPass = request.getParameter("oldPass");
			String newPass = request.getParameter("newPass");
			adminService.updatePass(id,oldPass, newPass);
			JsonUtils.writeSuccessJson("操做成功", "", response);
			return;
		} catch (ServiceException se) {
			se.printStackTrace();
			JsonUtils.writeBeanFailJson(se.getMessage(), response);
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeFailJson("操做失败!!" + e.getMessage(), response);
		}
		JsonUtils.writeListFailJson("操做失败!!", response);
	}

	protected void loginOut(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.getSession().removeAttribute("admin");
		response.sendRedirect(request.getContextPath() + "/login.jsp");
	}

}
